package com.demo.springmvc底层演示.demo1;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
@ComponentScan
public class WebConfig {

	// 内嵌web容器工厂
	@Bean
	public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
		return new TomcatEmbeddedServletContainerFactory();
	}
	
	// 创建DispatcherServlet
	@Bean
	public DispatcherServlet dispatcherServlet() {
		return new DispatcherServlet();
	}
	
	// 注册DispatcherServlet, springmvc的入口
	@Bean
	public ServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) {
		ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet, "/");
		// 一般情况下DispatcherServlet是在第一次访问时初始化，加上下面这段可以随tomcat一起初始化
		registration.setLoadOnStartup(1);
		return registration;
	}
	
	@Bean
	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		return new RequestMappingHandlerMapping();
	}
	
	@Bean
	public MyRequestMappingHandlerAdapter requestMappingHandlerAdapter() {
		MyRequestMappingHandlerAdapter handlerAdapter = new MyRequestMappingHandlerAdapter();
		List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<HandlerMethodReturnValueHandler>() {{
			add(new YmlReturnValueHandler());
		}};
		handlerAdapter.setCustomReturnValueHandlers(returnValueHandlers);
		return handlerAdapter;
	}
	
}
